package cn.itsource.ymcc.web.controller;

import cn.itsource.ymcc.constant.AliPayConstants;
import cn.itsource.ymcc.service.IPayOrderService;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.query.PayOrderQuery;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.result.PageList;
import cn.itsource.ymcc.vo.ApplyVo;
import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/payOrder")
public class PayOrderController {

    @Autowired
    public IPayOrderService payOrderService;

    @PostMapping("/apply")
    public JsonResult apply(@RequestBody ApplyVo applyVo){
        return JsonResult.success().setData(payOrderService.apply(applyVo));
    }

    /**
     * 支付宝的沙箱环境在哪里？  在线上的   让他来找你本地  找不到你本地
     * 解决文案2种
     *    1.你去买服务器 上线 绝对能找到
     *    2.内网穿透
     * @param request
     * @return
     */
    @PostMapping("/asyncNotify")
    public String asyncNotify(HttpServletRequest request){
        //思考的问题  性能、可读性
        //方案  两种  第一种创建实体类
        //          第二种直接就是map

        //数据转换
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,String> parameter = new HashMap<>();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();//有key有value
        for (Map.Entry<String, String[]> entry : entries) {
            parameter.put(entry.getKey(),entry.getValue()[0]==null?null:entry.getValue()[0]);
        }

        //我得让支付宝知道二次验签   在到支付宝做一次验证
        try {
            Boolean aBoolean = Factory.Payment.Common().verifyNotify(parameter);
//            if(aBoolean){
                //验证用户到底有没有付钱  --- 不相信就判断
                String trade_status = parameter.get("trade_status");
                if(AliPayConstants.TRADE_SUCCESS.equalsIgnoreCase(trade_status)
                        || AliPayConstants.TRADE_FINISHED.equalsIgnoreCase(trade_status)){
                    //成功之后做什么事情
                    payOrderService.paySuccess(parameter);
                    return "success";
                }else {
                    //失败之后做什么事情
                    //payFail();
                    return "failure";
                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "failure";
    }



    @GetMapping("/checkPayOrder/{orderNo}")
    public JsonResult checkPayOrder(@PathVariable("orderNo")String orderNo){
        PayOrder payOrder = payOrderService.getOne(new QueryWrapper<PayOrder>().eq("order_no", orderNo));
        return payOrder == null ? JsonResult.error("支付单找不到"):JsonResult.success();
    }


    /**
    * 保存和修改公用的
    */
    @PostMapping("/save")
    public JsonResult saveOrUpdate(@RequestBody PayOrder payOrder){
        if(payOrder.getId()!=null){
            payOrderService.updateById(payOrder);
        }else{
            payOrderService.save(payOrder);
        }
        return JsonResult.success();
    }

    /**
    * 删除对象
    */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        payOrderService.removeById(id);
        return JsonResult.success();
    }

    /**
   * 获取对象
   */
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id")Long id){
        return JsonResult.success().setData(payOrderService.getById(id));
    }


    /**
    * 查询所有对象
    */
    @GetMapping("/list")
    public JsonResult list(){
        return JsonResult.success().setData(payOrderService.list(null));
    }


    /**
    * 带条件分页查询数据
    */
    @PostMapping("/pagelist")
    public JsonResult page(@RequestBody PayOrderQuery query){
        Page<PayOrder> page = new Page<PayOrder>(query.getPageNo(), query.getPageSize());
        page = payOrderService.page(page);
        return JsonResult.success().setData(new PageList<PayOrder>(page.getTotal(), page.getRecords()));
    }
}
